#include "panelworkrequest.h"
#include "dlgeditworkrequest.h"
#include "pm/manager.h"
#include <boost/foreach.hpp>

PanelWorkRequest::PanelWorkRequest(wxWindow* parent)
: PanelWorkRequestGui(parent)
{
	m_listWR->InsertColumn(COL_NAME,   _("Name"));
	m_listWR->InsertColumn(COL_AMOUNT, _("Amount"), wxLIST_FORMAT_RIGHT);
	m_listWR->InsertColumn(COL_DATE,   _("Date"));
	
	wxTheApp->Connect(pmEVT_CONNECT_EVENTS, wxCommandEventHandler(PanelWorkRequest::OnConnectPmEvents), NULL, this);
	wxTheApp->Connect(pmEVT_PROJECT_LOADED, wxCommandEventHandler(PanelWorkRequest::OnProjectLoaded),   NULL, this);
	ConnectPmEvents();
}

void PanelWorkRequest::ConnectPmEvents()
{
	pmConnect(pmEVT_WORK_REQUEST_ADDED, pm::WorkRequest, PanelWorkRequest::OnWorkRequestAdded);
}

void PanelWorkRequest::DisconnectPmEvents()
{
	pmDisconnect(pmEVT_WORK_REQUEST_ADDED, pm::WorkRequest, PanelWorkRequest::OnWorkRequestAdded);
}

void PanelWorkRequest::AddWR(const pm::WorkRequest& wr)
{
	long item = m_listWR->InsertItem(m_listWR->GetItemCount(), wxEmptyString);
	SetWR(item, wr);
}

void PanelWorkRequest::SetWR(long item, const pm::WorkRequest& wr)
{
	m_listWR->SetItem(item, COL_NAME,   wr.name());
	m_listWR->SetItem(item, COL_AMOUNT, wxString::Format(wxT("%.2f"), wr.amount()));
	m_listWR->SetItem(item, COL_DATE,   wr.date().FormatISODate());
}

/**
 * \param event
 */
void PanelWorkRequest::OnConnectPmEvents(wxCommandEvent& event)
{
	event.Skip();
	if (event.GetInt()) {
		ConnectPmEvents();
	}
	else {
		DisconnectPmEvents();
	}
}

void PanelWorkRequest::OnProjectLoaded(wxCommandEvent& event)
{
	event.Skip();
wxLogMessage(wxT("PanelWorkRequest::OnProjectLoaded()"));
	
	m_listWR->DeleteAllItems();
	pm::GetWorkRequestsByProject crit(event.GetInt());
	pm::select(crit);
	
	BOOST_FOREACH(const pm::WorkRequest& wr, crit.m_result) {
		AddWR(wr);
	}
}

void PanelWorkRequest::OnWorkRequestAdded(pmEvent<pm::WorkRequest>& event)
{
	event.Skip();
	AddWR(event.GetContent());
}

void PanelWorkRequest::OnAddWR( wxCommandEvent& WXUNUSED(event) )
{
	DlgNewWorkRequest dlg(this);
	dlg.ShowModal();
}

void PanelWorkRequest::OnDelWR( wxCommandEvent& WXUNUSED(event) )
{
	
}
